package com.cellulargames.view;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class NumberPainter{

	private Image nums;
	
	private String numString;
	
	protected int width;
	
	protected int height;
	
	protected int digits;
	
	private int lastNum = -1;
	
	private int orientation;
	
	public static final int HORIZONTAL = 0;
	
	public static final int VERTICAL = 1;
	
	public NumberPainter(String file, int orientation){
		try{
			this.orientation = orientation;
			if( nums == null ){
				nums = Image.createImage(file);				
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private int[] digit;
	
	private int heightNumber;
	
	private int widthNumber;
	
	private int x, y;

	public void setNumber(int number) {
		
		switch( orientation ){
		
		case VERTICAL:
		
			if( width == 0 && height == 0 ){
				width = nums.getWidth();		
				height = nums.getHeight()/10;
			}
		
			if( lastNum != number ){
				numString = String.valueOf(number);				
				digits = numString.length();
				widthNumber = width;
				heightNumber = digits*height;			
				digit = new int[digits];		
				for( int i=0;i<digit.length;i++ ){
					digit[i] = Integer.parseInt( String.valueOf(numString.charAt(i)) );
				}
				lastNum = number;
			}
		
		break;
		
		case HORIZONTAL:
			
			if( width == 0 && height == 0 ){
				width = nums.getWidth()/10;		
				height = nums.getHeight();
			}
		
			if( lastNum != number ){
				numString = String.valueOf(number);				
				digits = numString.length();
				widthNumber = digits*width;
				heightNumber = height;			
				digit = new int[digits];			
				for( int i=0;i<digit.length;i++ ){
					digit[i] = Integer.parseInt( String.valueOf(numString.charAt(i)) );
				}
				lastNum = number;
			}
			
			break;
		
		}
	}
	
	public void setLocation(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	protected void paint(Graphics g) {
		
		
		switch ( orientation ) {
		
		case HORIZONTAL:
			int xc = x;
			for( int i=0;i<digits;i++ ){
				g.setClip(xc, y, width, height);
				g.drawImage(nums, xc - (width*digit[i]), y, Graphics.LEFT|Graphics.TOP);
				xc+=width;
			}
			break;
			
		case VERTICAL:
			xc = y;
			for( int i=digits-1;i>=0;i-- ){
				g.setClip(x, xc, width, height);
				g.drawImage(nums, x, xc - (height*digit[i]), Graphics.LEFT|Graphics.TOP);
				xc+=height;
			}
			break;
			
		}
		
	}
	
	protected int getWidthNumber(){
		return widthNumber;
	}
	
	protected int getHeightNumber(){
		return heightNumber;
	}

}
